<template>
  <div class="club-form">
    <h2>{{ isEdit ? '编辑社团' : '添加社团' }}</h2>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="form-container"
    >
      <el-form-item label="社团名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入社团名称"></el-input>
      </el-form-item>
      
      <el-form-item label="社团描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入社团描述"
        ></el-input>
      </el-form-item>
      
      <el-form-item label="负责人" prop="leaderId">
        <el-select v-model="form.leaderId" placeholder="请选择负责人" :disabled="!isAdmin && isEdit">
          <el-option
            v-for="user in userOptions"
            :key="user.id"
            :label="`${user.realName}(${user.username})`"
            :value="user.id"
          ></el-option>
        </el-select>
        <el-button style="margin-left: 10px;" @click="loadUsers" type="primary" plain>刷新</el-button>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getClubDetail, addClub, updateClub } from '@/api/club'
import { getUserList } from '@/api/user'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const formRef = ref(null)
const userOptions = ref([])

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const isAdmin = computed(() => userInfo.value.role === 'admin')

// 是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const form = reactive({
  name: '',
  description: '',
  leaderId: null
})

// 表单校验规则
const rules = reactive({
  name: [
    { required: true, message: '请输入社团名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入社团描述', trigger: 'blur' }
  ],
  leaderId: [
    { required: true, message: '请选择负责人', trigger: 'change' }
  ]
})

// 加载用户列表（作为负责人选项）
const loadUsers = async () => {
  try { 
    const res = await getUserList({
      pageSize: 1000,
      role: isAdmin.value ? '' : 'club_leader'  // 如果是管理员，可以选择任何用户，否则只能选择社团负责人
    })
    if (res.data && res.code === 200) {
      userOptions.value = res.data.list.filter(u=>u.role!=='admin')
         
      // 如果不是管理员且不是编辑模式，默认选择当前用户作为负责人
      if (!isAdmin.value && !isEdit.value) {
        form.leaderId = userInfo.value.id
      }
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取社团详情
const getClubInfo = async (id) => {
  try {
    const res = await getClubDetail(id)
    if (res.code === 200 && res.data) {
      // 填充表单数据
      form.name = res.data.name
      form.description = res.data.description
      form.leaderId = res.data.leaderId
    } else {
      ElMessage.error(res.message || '获取社团信息失败')
    }
  } catch (error) {
    console.error('获取社团详情出错:', error)
    ElMessage.error('获取社团信息失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      // 编辑社团
      const id = route.params.id
      const res = await updateClub(id, form)
      if (res.code === 200) {
        ElMessage.success('更新成功')
        goBack()
      } else {
        ElMessage.error(res.message || '更新失败')
      }
    } else {
      // 添加社团
      const res = await addClub(form)
      if (res.code === 200) {
        ElMessage.success('添加成功')
        goBack()
      } else {
        ElMessage.error(res.message || '添加失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('表单数据不完整或格式不正确')
  }
}

// 返回上一页
const goBack = () => {
  router.push('/clubs')
}

// 初始化
onMounted(() => {
  loadUsers()
  
  if (isEdit.value && route.params.id) {
    getClubInfo(route.params.id)
  }
})
</script>

<style scoped>
.club-form {
  padding: 20px;
}

.form-container {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 